<template>
  <div class="chat-container">
    <!-- 左侧用户列表 -->
    <div class="user-list">
      <div
          v-for="user in userList"
          :key="user.userId"
          :class="['user-item', selectedUserId === user.userId ? 'active' : '']"
          @click="selectUser(user)"
      >
        <div class="user-info">
          <div class="user-name">{{ user.userName }}</div>
          <div class="last-message">{{ user.lastMessage }}</div>
        </div>
        <div class="message-time">{{ formatTime(user.lastTime) }}</div>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-area">
      <div class="chat-header">
        <span>{{ selectedUser?.userName }}</span>
      </div>

      <div
          class="message-list"
          ref="messageList"
          @scroll="handleScroll"
      >
        <div v-if="hasMore" class="load-more" @click="loadMore">加载更多</div>
        <div
            v-for="msg in messages"
            :key="msg.id"
            :class="['message', msg.fromUserId === 'admin' ? 'message-right' : 'message-left']"
        >
          <div class="message-time">{{ formatTime(msg.sendTime) }}</div>
          <div class="message-content">{{ msg.content }}</div>
        </div>
      </div>

      <div class="input-area">
        <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            placeholder="请输入回复内容..."
            @keyup.enter.native="handleSend"
        />
        <el-button type="primary" @click="handleSend">发送</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import axios from '@/utils/axios'
import { formatDate, getRelativeTime } from '@/utils/date'

const messages = ref([])
const userList = ref([])
const selectedUserId = ref('')
const selectedUser = ref(null)
const inputMessage = ref('')
const hasMore = ref(true)
const pageSize = ref(20)
const ws = ref(null)

// 加载历史消息
const loadHistoryMessages = async () => {
  if (!selectedUserId.value || !hasMore.value) return

  try {
    const { data } = await axios.get('chatMessage/history', {
      params: {
        userId: 'admin',
        customerId: selectedUserId.value,
        limit: pageSize.value
      }
    })

    if (data.code === 200) {
      const newMessages = data.data.messages
      messages.value = [...newMessages, ...messages.value]
      hasMore.value = newMessages.length === pageSize.value
    }
  } catch (error) {
    console.error('加载历史消息失败:', error)
  }
}

// 选择用户
const selectUser = async (user) => {
  selectedUserId.value = user.userId
  selectedUser.value = user
  messages.value = []
  hasMore.value = true
  await loadHistoryMessages()
}

// 发送消息
const handleSend = () => {
  console.log("sendMessage")
  console.log(inputMessage.value,selectedUserId.value)
  if (!inputMessage.value.trim() || !selectedUserId.value) return

  const message = {
    fromUserId: 'admin',
    toUserId: selectedUserId.value,
    content: inputMessage.value,
    sendTime: new Date().toISOString(),
    messageType: 1
  }

  ws.value?.send(JSON.stringify(message))
  messages.value.push(message)
  inputMessage.value = ''
  scrollToBottom()
}

// 初始化WebSocket
const initWebSocket = () => {
  ws.value = new WebSocket('ws://localhost/websocket/customerService/admin')

  ws.value.onopen = () => {
    console.log('WebSocket连接成功')
  }

  ws.value.onmessage = (e) => {
    const message = JSON.parse(e.data)
    handleNewMessage(message)
  }

  ws.value.onerror = (e) => {
    console.error('WebSocket错误：', e)
  }

  ws.value.onclose = () => {
    console.log('WebSocket连接关闭')
  }
}

// 处理新消息
const handleNewMessage = (message) => {
  // 更新消息列表
  if(message.fromUserId === selectedUserId.value) {
    messages.value.push(message)
    scrollToBottom()
  }

  // 更新聊天列表
  const chatIndex = userList.value.findIndex(chat => chat.userId === message.fromUserId)
  if(chatIndex > -1) {
    userList.value[chatIndex].lastMessage = message.content
    userList.value[chatIndex].lastTime = message.sendTime
  } else {
    userList.value.unshift({
      userId: message.fromUserId,
      userName: `用户${message.fromUserId}`,
      lastMessage: message.content,
      lastTime: message.sendTime
    })
  }
}

// 滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    const container = document.querySelector('.message-list')
    container.scrollTop = container.scrollHeight
  }, 50)
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  // 对于聊天列表使用相对时间
  if (typeof time === 'string') {
    return getRelativeTime(time)
  }
  // 对于聊天消息使用完整时间
  return formatDate(time, 'yyyy-MM-dd HH:mm:ss')
}

onMounted(() => {
  initWebSocket()
})

onUnmounted(() => {
  if (ws.value) {
    ws.value.close()
  }
})
</script>

<style scoped>
.chat-container {
  height: 100%;
  display: flex;
  background: #fff;
}

.user-list {
  width: 300px;
  border-right: 1px solid #dcdfe6;
  overflow-y: auto;
}

.user-item {
  padding: 15px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
}

.user-item:hover {
  background: #f5f7fa;
}

.user-item.active {
  background: #ecf5ff;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.message-list {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.message {
  max-width: 80%;
  margin: 20px 0;
}

.message-left {
  margin-right: auto;
}

.message-right {
  margin-left: auto;
}

.message-content {
  padding: 10px 15px;
  border-radius: 4px;
  word-break: break-all;
}

.message-left .message-content {
  background: #f5f7fa;
}

.message-right .message-content {
  background: #ecf5ff;
  color: #409eff;
}

.input-area {
  padding: 20px;
  border-top: 1px solid #dcdfe6;
}

.load-more {
  text-align: center;
  color: #409eff;
  cursor: pointer;
  padding: 10px 0;
}
</style> 